﻿var CTSZ = {};
(function ($) {

    (function ($) {
        var __alert__ = $.alert;
        $.alert = function () {
            var arg, s = "";
            for (var i = 0; i < arguments.length; i++) {
                s += arguments[i] + "\n";
            }
            __alert__(s);
        }
        delete __alert__;

        String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }
        String.prototype.repeat = function (n) { var arr = new Array(n + 1); return arr.join(this); }
        String.prototype.padLeft = function (n, s) {
            // IE 不接受 substar 的第一个参数为负数的
            //return (s.repeat(n) + this).substr(-n);
            if ("000".substr(-2) != "000")
                return (s.repeat(n) + this).substr(-n);
            else
                return (s.repeat(n) + this).match(new RegExp("([\\s\\S]{" + n + "}$)"))[0];
        }
        String.prototype.padRight = function (n, s) {
            return (this + s.repeat(n)).substring(0, n);
        }
        String.prototype.queryString = function (key) {
            var sValue = this.match(new RegExp("[\?\&]" + key + "=([^\&]*)(\&?)", "i"));
            return sValue ? sValue[1] : sValue
        }

        String.prototype.setKeyValue = function (key, value) {
            if (this.queryString(key) != null) {
                var reg = new RegExp("([\?\&])(" + key + "=)([^\&]*)(\&?)", "i");
                return this.replace(reg, "$1$2" + value + "$4");
            } else {
                var add = arguments[2];
                if (add === true) {
                    return this + (this.indexOf("?") > -1 ? "&" : "?") + key + "=" + value;
                } else return this;
            }
        }

        /* decimalDigits 小数位数,默认为2, defaultValue 转换失败时,默认值  */
        String.prototype.asMoney = function (decimalDigits, defaultValue) {

            if (defaultValue == null)
                defaultValue = "";

            if (isNaN(decimalDigits)) {
                decimalDigits = 2;
            }

            if (!/(\d*)\.?(\d*)/.test(this.trim()))
                return defaultValue;

            var match = this.trim().match(/(\d*)\.?(\d*)/);
            if (match[1] + match[2] == "")
                return defaultValue;

            var part2 = match[2];
            if (part2.length < decimalDigits) {
                part2 = part2 + "0".repeat(decimalDigits - match[2].length);
            } else {
                part2 = part2.substring(0, decimalDigits);
            }

            if (match[1] != "")
                return match[1].split('').reverse().join('').replace(/(.{3}(?=.))/g, "$1,").split('').reverse().join('') + (part2 != "" ? "." + part2 : "");
            else
                return "0." + part2;
        }

        if (typeof (Element) != "undefined" && Element && Element.prototype && Element.prototype.__defineGetter__) {
            Element.prototype.__defineGetter__("outerHTML", function () {
                return (new XMLSerializer).serializeToString(this);
            });
        }

        // 如果转换失败，将返回 null
        // defaultValue 可以不填，默认为null
        String.prototype.toDate = function (defaultDate) {
            if (defaultDate != null && !(defaultDate instanceof Date)) {
                defaultDate = defaultDate.toString().toDate();
            }

            if (defaultDate == undefined)
                defaultDate = null;

            var date = null;
            var arr = new Array();
            if (this.indexOf("-") != -1) {
                arr = this.toString().split("-");
            } else if (this.indexOf("/") != -1) {
                arr = this.toString().split("/");
            } else {
                return defaultDate;
            }

            //yyyy-mm-dd || yyyy/mm/dd
            if (arr[0].length == 4) {
                date = new Date(arr[0], arr[1] - 1, arr[2]);
                if (date.getFullYear() == arr[0] && date.getMonth() == arr[1] - 1 && date.getDate() == arr[2]) {
                    return date;
                }
            }
            //dd-mm-yyyy || dd/mm/yyyy
            if (arr[2].length == 4) {
                date = new Date(arr[2], arr[1] - 1, arr[0]);
                if (date.getFullYear() == arr[2] && date.getMonth() == arr[1] - 1 && date.getDate() == arr[0]) {
                    return date;
                }
            }
            //mm-dd-yyyy || mm/dd/yyyy
            if (arr[2].length == 4) {
                date = new Date(arr[2], arr[0] - 1, arr[1]);
                if (date.getFullYear() == arr[2] && date.getMonth() == arr[0] - 1 && date.getDate() == arr[1]) {
                    return date;
                }
            }

            return defaultDate;
        }

        String.prototype.isDate = function () {
            return this.toDate() != null;
        }

        var __dateToString__ = Date.prototype.toString;
        /*仅支持以下格式：MM２长度月，yyyy四长度年，yy２长度年，dd２长日期, t / T AM or PM (小写返回小，大写返回大写)
        HH 2长度小时(24) hh2长度小时（12进制） mm 2长度分钟,ss 2长度秒
        M 1和2长度月, d 1或２长度日期 m,h,s 同上
        */
        Date.prototype.toString = function (fmt) {
            var date = this;
            if (!fmt)
                return __dateToString__.apply(this);

            var month = date.getMonth() + 1;
            var year = date.getFullYear();

            fmt = fmt.replace(/((yyyy)|(yy)|(MM)|(M)|(dd)|(d)|(HH)|(H)|(hh)|(h)|(mm)|(m)|(ss)|(s)|(T)|(t))/g, function (key) {
                //var leng = ma.length;
                switch (key) {
                    case "yyyy":
                        return year;
                        break;
                    case "yy":
                        return year % 100;
                        break;
                    case "MM":
                        return month.toString().padLeft(2, "0");
                        break;
                    case "M":
                        return month; break;
                    case "dd":
                        return date.getDate().toString().padLeft(2, "0");
                        break;
                    case "d":
                        return date.getDate();
                        break;
                    case "HH":
                        return date.getHours().toString().padLeft(2, "0");
                        break;
                    case "H":
                        return date.getHours();
                        break;
                    case "hh":
                        return (date.getHours() % 12).toString().padLeft(2, "0");
                        break;
                    case "h":
                        return date.getHours() % 12;
                        break;
                    case "mm":
                        return date.getMinutes().toString().padLeft(2, "0");
                        break;
                    case "m":
                        return date.getMinutes();
                        break;
                    case "ss":
                        return date.getSeconds().toString().padLeft(2, "0");
                        break;
                    case "s":
                        return date.getSeconds();
                        break;
                    case "t":
                        return date.getHours() > 11 ? "pm" : "am";
                        break;
                    case "T":
                        return date.getHours() > 11 ? "PM" : "AM";
                        break;
                    default:
                        return key;
                }
            });
            return fmt;
        }

        /* 
        返回新值，並且不改變舊值
        datePart yy:year, m:month, d: date,h:hour, mi:minute, s:second, ms:毫秒
        */
        Date.prototype.add = function (datePart, v) {
            var reg = /^((yy)|(m)|(d)|(h)|(mi)|(s)|(ms))$/i;
            if (!reg.test(datePart)) {
                throw new Error("Invalid argument datePart, yy:year, m:month, d: date,h:hour, mi:minute, s:second, ms:millisecond");
            }

            if (isNaN(v)) {
                return this;
            }

            // Date 是地址引用
            var tmp = new Date(this.valueOf());

            var key = datePart.match(reg)[0].toUpperCase();
            var vv = this.valueOf();
            switch (key) {
                case "YY":
                    vv = tmp.setFullYear(this.getFullYear() + v);
                    break;
                case "M":
                    vv = tmp.setMonth(this.getMonth() + v);
                    break;
                case "D":
                    vv = tmp.setDate(this.getDate() + v);
                    break;
                case "H":
                    vv = tmp.setHours(this.getHours() + v);
                    break;
                case "MI":
                    vv = tmp.setMinutes(this.getMinutes() + v);
                    break;
                case "S":
                    vv = tmp.setSeconds(this.getSeconds() + v);
                    break;
                case "MS":
                    vv = tmp.setMilliseconds(this.getMilliseconds() + v);
                    break;
            }
            return new Date(vv);
        }
    })(window);


    $.isObject = function (p) { return "object" == typeof (p) }
    $.isFunction = function (p) { return p instanceof Function; }
    $.$ = function (p, doc) { return $.isObject(p) ? p : (doc || document).getElementById(p); }
    $.$c = function (tag) { return document.createElement(tag); }
    $.$tag = function (tag, node) { return $.$(undefined == node || null == node ? document : node).getElementsByTagName(tag); }
    $.$name = function (name, node) { return $.$(undefined == node || null == node ? document : node).getElementsByName(name); }
    $.$class = function (className, obj) {
        obj = $.$(obj) || document;
        var objs = obj.all || obj.getElementsByTagName("*");
        var o, i, arr = [];
        var classNames = "";
        className = "," + className + ",";
        for (i = 0; o = objs[i]; i++) {
            classNames = "," + o.className.split(/\s+/).join(",") + ",";
            if (classNames.indexOf(className) >= 0) {
                arr.push(o);
            }
        }
        delete objs;
        return arr;
    }

    $.addEvent = function (obj, type, fun) {
        obj = CTSZ.$(obj);

        if (obj.attachEvent) {
            if (!/^on/.test(type))
                type = 'on' + type;
            obj.attachEvent(type, fun);
        } else if (obj.addEventListener) {
            if (/^on/.test(type))
                type = type.substr(2);
            obj.addEventListener(type, fun, false);
        }
    }

    $.doFunction = function (fun) {
        var args = [], i;
        for (i = 1; i < arguments.length; i++) {
            args.push(arguments[i]);
        }
        return function () {
            fun.apply(null, args);
            delete args;
        };
    }

    $.addClass = function (obj, className) {
        obj = $.$(obj);
        if (!obj || obj.className == undefined)
            return;

        var cn = " " + obj.className + " ";
        if (cn.indexOf(" " + className + " ") == -1)
            obj.className = cn.trim() + " " + className.trim();
    }

    $.removeClass = function (obj, className) {
        obj = $(obj);
        if (!obj || obj.className == undefined)
            return;

        className = className.trim().replace("*", "\\w*");
        var cn = " " + obj.className + " ";
        var reg = new RegExp("\\s" + className + "\\s", 'g')
        obj.className = cn.replace(reg, "").trim();
    }

    var fixCss = function () { return arguments[1].toUpperCase(); }

    var style = null;
    var styleSheet = null;
    $.addRule = function (p, k, asNew) {
        if (asNew !== true) {
            if (style == null) {
                style = $.$c("STYLE");
                $.$tag("HEAD")[0].appendChild(style);
                styleSheet = style.styleSheet || style.sheet;
            }
        } else {
            style = $.$c("STYLE");
            $.$tag("HEAD")[0].appendChild(style);
            styleSheet = style.styleSheet || style.sheet;
        }

        if (styleSheet.addRule) {
            var rs = p.split(',');
            for (var i = 0; i < rs.length; i++)
                styleSheet.addRule(rs[i], k);
        } else if (styleSheet.insertRule) {
            styleSheet.insertRule(p + "{" + k + "}", styleSheet.cssRules.length);
        }
    }

    $.css = function (obj, rules) {
        obj = $.$(obj);
        if (!obj || !obj.style)
            return;

        var rule;
        for (rule in rules) {
            rule = rule.replace(/\-(\w)/ig, fixCss);
            if (rule == 'float' && obj.currentStyle) rule = 'styleFloat';

            if (/alpha|opacity/i.test(rule)) {
                if (obj.style.filter) {
                    obj.style.filter = 'alpha(opacity:' + rules[rule] + ')';
                } else {
                    obj.style.opacity = rules[rule] / 100;
                }
            } else {
                try {
                    obj.style[rule] = rules[rule] + (/(width|height|positionX|positionY|top|left|right|bottom|fontSize)$/i.test(rule) && !isNaN(rules[rule]) ? 'px' : '')
                } catch (ex) {

                }
            }
        }
    }

    $.getAbsPos = function (pTarget) {
        pTarget = $.$(pTarget);

        if (!pTarget.getBoundingClientRect) {
            var x_ = y_ = 0;

            while (pTarget.offsetParent) {
                x_ += pTarget.offsetLeft;
                y_ += pTarget.offsetTop;
                pTarget = pTarget.offsetParent;
            }
            x_ += pTarget.offsetLeft;
            y_ += pTarget.offsetTop;
            return { x: x_, y: y_ }
        } else {
            //Chrome 下 document.documentElement.scrollXXX一直是0
            //var body = document.compatMode == 'CSS1Compat' ? document.documentElement : document.body;
            var b1 = document.body;
            var b2 = document.documentElement;
            var rect = pTarget.getBoundingClientRect()
            //return {x:rect.left + body.scrollLeft,y:rect.top + body.scrollTop};
            return { x: rect.left + (b2.scrollLeft || b1.scrollLeft), y: rect.top + (b2.scrollTop || b1.scrollTop) };
        }
    }

    $.Cookie = {};
    (function ($) {

        $.getExpires = function (y, m, d, h, i, s, ms) {
            var date = new Date();
            y = isNaN(y) ? date.getFullYear() : y;
            m = isNaN(m) ? date.getMonth() : m - 1;
            d = isNaN(d) ? date.getDate() : d;

            h = isNaN(h) ? date.getHours() : h;
            i = isNaN(i) ? date.getMinutes() : i;
            s = isNaN(s) ? date.getSeconds() : s;
            ms = isNaN(ms) ? date.getMilliseconds() : ms;

            return new Date(y, m, d, h, i, s, ms).toUTCString();
        }

        $.getExpiresByUTCString = function (UTCString) {
            var s = new Date(UTCString).toUTCString();
            if (s == 'NaN' || s == 'Invalid Date')
                return null; // IE,Opera NaN , FF,Safari Invalid Date;
            else
                return s;
        }


        $.set = function (k, v, expires, path, domain, secure) {
            var cookie = k + '=' + encodeURIComponent(v);

            if (expires) cookie += "; expires=" + expires;
            if (path) cookie += "; path=" + path;
            if (domain) cookie += "; domain=" + domain;
            if (secure) cookie += "; secure";
            document.cookie = cookie;
        }


        /*
        以前是把所有 cookie 都取出放到一个对象里，在 get 的时候，直接从那个对象里取来，现在想想，那样并不正确。因为假如某个 cookie 的过期时间过了，那个对象并没有更新。
        */
        $.get = function (k) {
            var cks = document.cookie.split(';');
            var t;
            for (var i = 0; i < cks.length; i++) {
                t = cks[i].split('=');
                if (k == t[0].trim()) return t.length >= 2 ? decodeURIComponent(t[1]) : "";
            }
            return null;
        }

        $.remove = function (k, path, domain) {
            $.set(k, '', $.getExpires(new Date().getFullYear() - 1), path, domain);
        }

        $.empty = function (path, domain) {
            var cks = document.cookie.split(';');
            var t;
            for (var i = 0; i < cks.length; i++) {
                $.remove(cks[i].split('=')[0].trim(), path, domain);
            }
        }
    })($.Cookie);

    $.HTML = {};
    (function ($) {

        var moneyInput = function (obj, decimalDigits, defaultValue) {
            obj = CTSZ.$(obj);
            obj.value = obj.value.replace(",", "").asMoney(decimalDigits, defaultValue);
        }

        /* decimalDigits 小数位数,默认为2, defaultValue 转换失败时,默认值  */
        $.asMoneyInput = function (obj, decimalDigits, defaultValue) {
            var obj = CTSZ.$(obj);
            if (!obj)
                return;

            //CTSZ.addEvent(obj, "input", CTSZ.doFunction(moneyInput, obj , decimalDigits, defaultValue));
            CTSZ.addEvent(obj, "blur", CTSZ.doFunction(moneyInput, obj, decimalDigits, defaultValue));
            moneyInput(obj, decimalDigits, defaultValue);
        }

    })($.HTML);

    $.Storage = {};
    (function ($) {

        var storage;
        var useBehavior = false;
        var support = true;

        var init = function () {

            if (window.globalStorage)
                storage = window.globalStorage[location.hostname];
            else if (window.localStorage)
                storage = window.localStorage;
            else {
                if (!document.body)
                    document.write("<body></body>");
                storage = document.createElement("JStorage")
                document.documentElement.insertBefore(storage, document.body);
                if (storage.addBehavior) {
                    storage.addBehavior("#default#userData");
                    useBehavior = true;
                } else {
                    support = false;
                }
            }
        }
        init();

        $.setItem = function (k, v) {
            if (!support)
                return;

            if (!useBehavior) {
                storage.setItem(k, v);
            } else {
                storage.setAttribute(k, v)
                storage.save("JStorage");
            }
        }

        $.getItem = function (k) {
            if (!support)
                return '';

            if (!useBehavior)
                return storage.getItem(k);
            else {
                storage.load("JStorage");
                return storage.getAttribute(k)
            }
        }

        $.removeItem = function (k) {
            if (!support) return;

            if (!useBehavior)
                storage.removeItem(k);
            else {
                storage.load("JStorage");
                storage.removeAttribute(k);
            }
        }

    })($.Storage);

})(CTSZ);


if (typeof (JSON) == "undefined")
    JSON = {};

if (!JSON.stringify) {
    if (Object.toSource) {
        JSON.stringify = Object.toSource;
    } else {
        JSON.stringify = (function () {
            /**
            * 字符串处理时需要转义的字符表
            * @private
            */
            var escapeMap = {
                "\b": '\\b',
                "\t": '\\t',
                "\n": '\\n',
                "\f": '\\f',
                "\r": '\\r',
                '"': '\\"',
                "\\": '\\\\'
            };

            /**
            * 字符串序列化
            * @private
            */
            function encodeString(source) {
                if (/["\\\x00-\x1f]/.test(source)) {
                    source = source.replace(
                /["\\\x00-\x1f]/g,
                function (match) {
                    var c = escapeMap[match];
                    if (c) {
                        return c;
                    }
                    c = match.charCodeAt();
                    return "\\u00"
                            + Math.floor(c / 16).toString(16)
                            + (c % 16).toString(16);
                });
                }
                return '"' + source + '"';
            }

            /**
            * 数组序列化
            * @private
            */
            function encodeArray(source) {
                var result = ["["],
                    l = source.length,
                    preComma, i, item;

                for (i = 0; i < l; i++) {
                    item = source[i];

                    switch (typeof item) {
                        case "undefined":
                        case "function":
                        case "unknown":
                            break;
                        default:
                            if (preComma) {
                                result.push(',');
                            }
                            result.push(JSON.stringify(item));
                            preComma = 1;
                    }
                }
                result.push("]");
                return result.join("");
            }

            /**
            * 处理日期序列化时的补零
            * @private
            */
            function pad(source) {
                return source < 10 ? '0' + source : source;
            }

            /**
            * 日期序列化
            * @private
            */
            function encodeDate(source) {
                return '"' + source.getFullYear() + "-"
                + pad(source.getMonth() + 1) + "-"
                + pad(source.getDate()) + "T"
                + pad(source.getHours()) + ":"
                + pad(source.getMinutes()) + ":"
                + pad(source.getSeconds()) + '"';
            }

            return function (value) {
                switch (typeof value) {
                    case 'undefined':
                        return 'undefined';

                    case 'number':
                        return isFinite(value) ? String(value) : "null";

                    case 'string':
                        return encodeString(value);

                    case 'boolean':
                        return String(value);

                    default:
                        if (value === null) {
                            return 'null';
                        } else if (value instanceof Array) {
                            return encodeArray(value);
                        } else if (value instanceof Date) {
                            return encodeDate(value);
                        } else {
                            var result = ['{'],
                    encode = JSON.stringify,
                    preComma,
                    item;

                            for (var key in value) {
                                if (Object.prototype.hasOwnProperty.call(value, key)) {
                                    item = value[key];
                                    switch (typeof item) {
                                        case 'undefined':
                                        case 'unknown':
                                        case 'function':
                                            break;
                                        default:
                                            if (preComma) {
                                                result.push(',');
                                            }
                                            preComma = 1;
                                            result.push(encode(key) + ':' + encode(item));
                                    }
                                }
                            }
                            result.push('}');
                            return result.join('');
                        }
                }
            };
        })();
    }
}